package com.situ.onlinebookstore.back.controller;

import com.situ.onlinebookstore.back.service.GoodsService;
import com.situ.onlinebookstore.common.entity.Goods;
import com.situ.onlinebookstore.common.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/goods")
@RequiredArgsConstructor
public class GoodsController {
    private final GoodsService goodsService;

    //添加
    @RequestMapping("/add")
    public Result add(Goods goods,@RequestParam("pic") String[] pics) {
        //1-获取参数
        try {
            //2-校验参数

            goodsService.add(goods,pics);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //修改
    @RequestMapping("/edit")
    public Result edit(Goods goods, @RequestParam(value = "pic", defaultValue = "") String[] pics) {
        //1-获取参数
        try {
            //2-校验参数

            goodsService.edit(goods,pics);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    //根据ID查询
    @RequestMapping("/getById")
    public Result getById(Integer id){
        return Result.ok(goodsService.getById(id));
    }

    @RequestMapping("/search")
    //查询所有
    public Result search(Integer page,Integer limit,Goods goods){
        if (page == null){
            return Result.ok(goodsService.search(goods));
        }else {
            return Result.ok(goodsService.searchForPage(page,limit,goods));
        }
    }
}
